package com.example.exception;

import com.example.util.CommonUtils;

import java.util.concurrent.CompletableFuture;

public class HandleDemo {
    public static void main(String[] args) {
        CommonUtils.printThreadLog("main start");

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("初始 supplyAsync");
            // int a = 10 / 0;
            return "result1";
        }).handle((result, exception) -> {
            CommonUtils.printThreadLog("handle1中的result = " + result);
            if (exception != null) {
                System.out.println("出现异常：" + exception.getMessage());
                return "unknown1";
            }
            return result;
        }).thenApply(result -> {
            String str = null;
            str.length();
            return result + " result2";
        }).handle((result, exception) -> {
            CommonUtils.printThreadLog("handle2中的result = " + result);
            if (exception != null) {
                System.out.println("出现异常：" + exception.getMessage());
                return "unknown2";
            }
            return result;
        }).thenApply(result -> {
            return result + " result3";
        }).exceptionally(exception -> {
            System.out.println("出现异常：" + exception.getMessage());
            exception.printStackTrace();
            return "unknown";
        });

        CommonUtils.printThreadLog("main continue");

        String result = future.join();
        CommonUtils.printThreadLog("结果：" + result);

        CommonUtils.printThreadLog("main end");

    }
}
